import 'dart:developer' as developer;

import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';

final log = Logger('GlobalLogger');

void registerLogger() {
  Logger.root.level = kDebugMode ? Level.ALL : Level.WARNING;
  Logger.root.onRecord.listen((record) {
    if (kDebugMode) {
      developer.log(
        _msgWith(record),
        time: record.time,
        sequenceNumber: record.sequenceNumber,
        level: record.level.value,
        name: record.loggerName,
        zone: record.zone,
        error: record.error,
        stackTrace: record.stackTrace,
      );
      return;
    }
  });
}

String _levelFlag(Level level) {
  if (level == Level.FINE) return '🤍 ';
  if (level == Level.INFO) return '💚 ';
  if (level == Level.WARNING) return '💛 ';
  if (level == Level.SEVERE) return '💔 ';
  return '${level.name} ';
}

String _msgWith(LogRecord record) {
  final msg = '${_levelFlag(record.level)}${record.time}: ${record.message}';
  if (record.level == Level.WARNING) {
    return '\x1B[33m$msg\x1B[0m';
  }
  if (record.level == Level.SEVERE) {
    return '\x1B[31m$msg\x1B[0m';
  }
  return '\x1B[34m$msg\x1B[0m';
}
